const WebSocket = require('ws');
const axios = require('axios');

class DeputyAttributesTester {
    constructor() {
        this.ws = null;
        this.baseUrl = 'http://localhost:3000';
        this.wsUrl = 'ws://localhost:3000/user-service/websocket';
        this.token = null;
        this.characterId = null;
    }

    async login() {
        try {
            console.log('🔐 正在登录...');
            const response = await axios.post(`${this.baseUrl}/auth/login`, {
                username: 'testuser',
                password: 'testpass'
            });

            if (response.data.code === 0) {
                this.token = response.data.data.token;
                this.characterId = response.data.data.character.id;
                console.log(`✅ 登录成功，角色ID: ${this.characterId}`);
                return true;
            } else {
                console.log('❌ 登录失败:', response.data.msg);
                return false;
            }
        } catch (error) {
            console.log('❌ 登录请求失败:', error.message);
            return false;
        }
    }

    connectWebSocket() {
        return new Promise((resolve, reject) => {
            console.log('🔌 正在连接WebSocket...');
            this.ws = new WebSocket(this.wsUrl);

            this.ws.on('open', () => {
                console.log('✅ WebSocket连接成功');
                // 发送认证消息
                this.ws.send(JSON.stringify({
                    type: 'auth',
                    token: this.token,
                    characterId: this.characterId
                }));
                resolve();
            });

            this.ws.on('message', (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    console.log('📨 接收到数据:', JSON.stringify(message, null, 2));
                } catch (error) {
                    console.log('📨 接收到原始数据:', data.toString());
                }
            });

            this.ws.on('error', (error) => {
                console.log('❌ WebSocket错误:', error.message);
                reject(error);
            });

            this.ws.on('close', () => {
                console.log('🔌 WebSocket连接已关闭');
            });
        });
    }

    async testDeputyAttributes(deputyId) {
        return new Promise((resolve) => {
            console.log(`\n🧪 测试1110指令 - 查询副将属性信息 (副将ID: ${deputyId})`);

            const message = {
                c: 1110,
                d: {
                    cid: deputyId
                }
            };

            console.log('📤 发送的数据:', JSON.stringify(message, null, 2));

            // 设置消息监听器
            const messageHandler = (data) => {
                try {
                    const response = JSON.parse(data.toString());
                    if (response.act_id === 1110) {
                        this.ws.off('message', messageHandler);
                        console.log('✅ 1110指令响应成功');
                        console.log('📊 副将属性信息:');
                        console.log(`   当前攻击力: ${response.data.ap}`);
                        console.log(`   当前血量: ${response.data.hp}`);
                        console.log(`   当前精力: ${response.data.mp}`);
                        console.log(`   当前速度: ${response.data.sp}`);
                        console.log(`   当前成长率: ${response.data.czl}`);
                        console.log(`   攻击力范围: ${response.data.apMin} - ${response.data.apMax}`);
                        console.log(`   血量范围: ${response.data.hpMin} - ${response.data.hpMax}`);
                        console.log(`   精力范围: ${response.data.mpMin} - ${response.data.mpMax}`);
                        console.log(`   速度范围: ${response.data.spMin} - ${response.data.spMax}`);
                        console.log(`   成长率范围: ${response.data.czlMin} - ${response.data.czlMax}`);
                        console.log(`   将军令数量: ${response.data.jjlc}`);
                        resolve(response);
                    }
                } catch (error) {
                    // 忽略解析错误，继续等待正确的响应
                }
            };

            this.ws.on('message', messageHandler);

            // 发送请求
            this.ws.send(JSON.stringify(message));

            // 设置超时
            setTimeout(() => {
                this.ws.off('message', messageHandler);
                console.log('⏰ 请求超时');
                resolve(null);
            }, 10000);
        });
    }

    async runTests() {
        try {
            // 登录
            const loginSuccess = await this.login();
            if (!loginSuccess) {
                return;
            }

            // 连接WebSocket
            await this.connectWebSocket();

            // 等待一下让连接稳定
            await new Promise(resolve => setTimeout(resolve, 1000));

            // 测试1110指令 - 使用一个存在的副将ID
            const testDeputyId = 244256; // 使用用户提供的副将ID
            await this.testDeputyAttributes(testDeputyId);

            // 测试不存在的副将ID
            console.log('\n🧪 测试1110指令 - 查询不存在的副将');
            await this.testDeputyAttributes(999999);

            console.log('\n✅ 所有测试完成');

        } catch (error) {
            console.log('❌ 测试过程中发生错误:', error.message);
        } finally {
            if (this.ws) {
                this.ws.close();
            }
        }
    }
}

// 运行测试
const tester = new DeputyAttributesTester();
tester.runTests().catch(console.error);
